using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Fuzzware.Common;
using Fuzzware.Common.Encoding;
using Fuzzware.Common.DataSchema;

namespace Fuzzware.ConvertFromXML.Processors
{
    class KeepBytesFns
    {
        private int GetLength(String PItext, String FnName)
        {
            // Get number of bytes to keep
            String StrLength = "";
            if (!XMLProcInstCommands.GetCommandValue(PItext, FnName, out StrLength))
            {
                Log.Write(MethodBase.GetCurrentMethod(), "Could not get number of bytes to keep from '" + PItext + "'", Log.LogType.Error);
            }
            int Length = 0;
            if (!Int32.TryParse(StrLength, out Length))
            {
                Log.Write(MethodBase.GetCurrentMethod(), "Could not convert number of bytes to an Int32 from '" + PItext + "'", Log.LogType.Error);
            }
            return Length;
        }

        /// <summary>
        /// Keep the End Bytes of the array.
        /// e.g. '000102030405060708'(hex) with KeepEndBytes="5" would return '0405060708'(hex)
        /// </summary>
        public void KeepEndBytes(ref byte[] operand, IOutputNode SourceNode, IOutputNode TargetNode)
        {
            Array.Reverse(operand);
            // Assume the operand is binary
            int Length = 2*GetLength(TargetNode.PIText, "KeepEndBytes");
            Array.Resize<byte>(ref operand, (Length > operand.Length?operand.Length:Length));
            Array.Reverse(operand);
        }
    
        /// <summary>
        /// Keep the Start Bytes of the array.
        /// e.g. '000102030405060708'(hex) with KeepStartBytes="5" would return '0001020304'(hex)
        /// </summary>
        public void KeepStartBytes(ref byte[] operand, IOutputNode SourceNode, IOutputNode TargetNode)
        {
            int Length = 2*GetLength(TargetNode.PIText, "KeepStartBytes");
            Array.Resize<byte>(ref operand, (Length > operand.Length?operand.Length:Length));
        }
    }
}
